//
//  InvestmentTableViewController.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/27.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "InvestmentTableViewController.h"
#import "InvestmentCell.h"
#import "InvestDetailTableViewController.h"
#import "InvestListModel.h"
#import "DZHeadOption.h"
@interface InvestmentTableViewController ()<DZHeadOptionDelegate,UITableViewDataSource,UITableViewDelegate> {
    NSMutableArray *holdArray;
    NSMutableArray *paymentArray;
    NSArray *showArray;
    NSInteger currentType;
    NSInteger holdPage;
    NSInteger paymentPage;
    UIView *backView;
}

@property (strong, nonatomic) UISegmentedControl *segment;
@property (strong, nonatomic) UITableView *tableView;
@end

@implementation InvestmentTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"投资金额"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    NSLog(@"%@",self.view);
    holdArray = [NSMutableArray array];
    paymentArray = [NSMutableArray array];
    showArray = [NSArray array];
    currentType = 0;
    holdPage = paymentPage = 1;
    [self setHeadView];
    [self setTableView];
}

- (void)setTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 108, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = BACKGROUND_COLOR;
    self.tableView.mj_header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadRequestData)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestNewData)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setHeadView {
    DZHeadOption *view = [[DZHeadOption alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 44)];
    view.titleArray = @[@"持有中",@"已回款"];
    view.delegate = self;
    [self.view addSubview:view];
}
- (void)DZHeadOptionView:(DZHeadOption *)DZHeadOption currectIndex:(NSInteger)currectIndex {
    [backView removeFromSuperview];
    backView = nil;
    currentType = currectIndex;
    switch (currentType) {
        case 0:showArray = [NSArray arrayWithArray:holdArray];break;
        case 1:showArray = [NSArray arrayWithArray:paymentArray];break;
    }
    [self.tableView reloadData];
    
    if (!showArray.count) {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)buildNoDataViewWithStatus:(NSInteger)status {
    UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, (SCREEN_HEIGHT-SCREEN_WIDTH)/2.0, SCREEN_WIDTH, SCREEN_WIDTH)];
    bkView.backgroundColor = BACKGROUND_COLOR;
    [self.tableView addSubview:bkView];
    UIImageView *img = [[UIImageView alloc] init];
    [bkView addSubview:img];
    UILabel *tipLab = [[UILabel alloc] init];
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.textColor = [UIColor lightGrayColor];
    tipLab.font = [UIFont systemFontOfSize:15];
    [bkView addSubview:tipLab];
    
    if (status == 1) {
        img.image = [UIImage imageNamed:@"空订单"];
        tipLab.text = @"暂时没有相关数据~";
    } else {
        img.image = [UIImage imageNamed:@"无网络"];
        tipLab.text = @"网络连接异常，请检查网络";
        
    }
    
    CGSize size = img.image.size;
    
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bkView.mas_centerX);
        make.width.mas_equalTo(size.width);
        make.height.mas_equalTo(size.height);
        make.top.equalTo(@12);
    }];
    [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(bkView.mas_leading);
        make.trailing.equalTo(bkView.mas_trailing);
        make.top.equalTo(img.mas_bottom).offset(8);
        make.height.equalTo(@30);
    }];
    if (status == 0) {
        UIButton *reconnectBtn = [[UIButton alloc] init];
        [reconnectBtn setTitle:@"重新连接" forState:UIControlStateNormal];
        [reconnectBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        reconnectBtn.layer.masksToBounds = YES;
        reconnectBtn.layer.cornerRadius = BTN_RADIUS;
        reconnectBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        reconnectBtn.layer.borderWidth = 1;
        [reconnectBtn addTarget:self action:@selector(loadRequestData) forControlEvents:UIControlEventTouchUpInside];
        [bkView addSubview:reconnectBtn];
        
        [reconnectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(100, 30));
            make.centerX.equalTo(bkView.mas_centerX);
            make.top.equalTo(tipLab.mas_bottom).offset(8);
        }];
    }
    backView = bkView;
}

- (void)loadRequestData {
    [backView removeFromSuperview];
    backView = nil;
    __block NSInteger theType = currentType;
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Order/getBuyOrderList";
    request.httpMethod = @"GET";
    request.params = @{@"order_type":[NSString stringWithFormat:@"%ld",theType+1],
                       @"p":@1,
                       @"pagesize":@10};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            [self reloadRequestOparation:response withType:theType];
        }else if (model.rt == 0) {
            [CommTools getRnsAndSid:^(id result) {
             [DZNetAPI request:request success:^(id response) {
                 [self reloadRequestOparation:response withType:theType];
             } failure:^(NSError *error) {
             }];
            }];
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)reloadRequestOparation:(NSDictionary *)responseObject withType:(NSInteger)theType {
    if (responseObject == nil) {
        if (userValue(HOSTTEL)) {
            LoginViewController *login = [[LoginViewController alloc] init];
            login.telNum = userValue(HOSTTEL);
            [self.navigationController pushViewController:login animated:YES];
        } else {
            RegisterViewController *join = [[RegisterViewController alloc] init];
            [self.navigationController pushViewController:join animated:YES];
        }
    } else {
        [theUser setObject:responseObject[HKNAME] forKey:HKNAME];
        [theUser synchronize];
        if ([responseObject[@"rt"] integerValue] == 1) {
//            NSLog(@"页数：%@",responseObject[@"data"][@"p"]);
            NSInteger thePage = [responseObject[@"data"][@"p"] integerValue];
            [self loadDataToShowView:responseObject[@"data"][@"list"] refreshType:NO type:theType page:thePage];
        }
    }
}

- (void)requestNewData {
    __block NSInteger theType = currentType;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",theType+1],@"order_type",@10,@"pagesize", nil];
    NSLog(@"page: %ld",holdPage);
    switch (theType) {
        case 0:[params setObject:[NSString stringWithFormat:@"%ld",holdPage+1] forKey:@"p"];break;
        case 1:[params setObject:[NSString stringWithFormat:@"%ld",paymentPage+1] forKey:@"p"];break;
    }
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.httpMethod = @"GET";
    request.requestUrl = @"Order/getBuyOrderList";
    request.params = params;
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            [self reloadNewRequestOpataion:response withType:theType];
        }else if (model.rt == 0){
            [CommTools getRnsAndSid:^(id result) {
                [DZNetAPI request:request success:^(id response) {
                    [self reloadNewRequestOpataion:response withType:theType];
                } failure:^(NSError *error) {
                }];
            }];
        }
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)reloadNewRequestOpataion:(NSDictionary *)responseObject withType:(NSInteger)theType {
    if (responseObject == nil) {
        if (userValue(HOSTTEL)) {
            LoginViewController *login = [[LoginViewController alloc] init];
            login.telNum = userValue(HOSTTEL);
            [self.navigationController pushViewController:login animated:YES];
        } else {
            RegisterViewController *join = [[RegisterViewController alloc] init];
            [self.navigationController pushViewController:join animated:YES];
        }
    } else {
        [theUser setObject:responseObject[HKNAME] forKey:HKNAME];
        [theUser synchronize];
        if ([responseObject[@"rt"] integerValue] == 1) {
            NSInteger thePage = [responseObject[@"data"][@"p"] integerValue];
            [self loadDataToShowView:responseObject[@"data"][@"list"] refreshType:YES type:theType page:thePage];
        }
    }
}

- (void)loadDataToShowView:(NSArray *)dataArray refreshType:(BOOL)refreshType type:(NSInteger )theType page:(NSInteger)thePage {
    if (theType == 0) {
        if (refreshType == NO) {
            [holdArray removeAllObjects];
        }
        for (NSDictionary *dict in dataArray) {
            InvestListModel *model = [InvestListModel modelWithDict:dict];
            [holdArray addObject:model];
        }
        showArray = [NSArray arrayWithArray:holdArray];
    } else if (currentType == 1) {
        if (refreshType == NO) {
            [paymentArray removeAllObjects];
        }
        for (NSDictionary *dict in dataArray) {
            InvestListModel *model = [InvestListModel modelWithDict:dict];
            [paymentArray addObject:model];
        }
        showArray = [NSArray arrayWithArray:paymentArray];
    }
    
    if (showArray.count == 0) {
        [self buildNoDataViewWithStatus:1];
    }
    
    [self calculateRefreshPage:dataArray refreshType:refreshType type:theType page:thePage];
    [self.tableView reloadData];
}

- (void)calculateRefreshPage:(NSArray *)dataArray refreshType:(BOOL)refreshType type:(NSInteger)theType page:(NSInteger)thePage {
    //    NSLog(@"dataArray: %@",dataArray);
    if (dataArray.count == 0) {
//        NSLog(@"no data !  currrentType: %ld   currentPage: %ld",theType,thePage);
        return;
    }
    if (refreshType == NO) {
        switch (theType) {
            case 0:holdPage = 1;break;
            case 1:paymentPage = 1;break;
        }
    } else {
        switch (theType) {
            case 0:holdPage = thePage;break;
            case 1:paymentPage = thePage;break;
        }
    }
    NSLog(@"currrentType: %ld   currentPage: %ld",theType,thePage);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 78;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 6;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [showArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView registerNib:[UINib nibWithNibName:@"InvestmentCell" bundle:nil] forCellReuseIdentifier:INVEST_CELL];
    InvestmentCell *cell = [InvestmentCell cellWithTableView:tableView];
    cell.segementValue = currentType;
    [cell setUpCell:showArray[indexPath.section]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    InvestDetailTableViewController *investDetail = [[InvestDetailTableViewController alloc] init];
    InvestListModel *model = showArray[indexPath.section];
    [investDetail setupTitleView:[NSString stringWithFormat:@"%@详情",model.product_name]];
    investDetail.investModel = model;
    investDetail.segmentValue = currentType;
    [self.navigationController pushViewController:investDetail animated:YES];
}

@end
